// +----------------------------------------------------------------------
// | CmsWing [ 美业管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 psi All rights reserved.
// +----------------------------------------------------------------------
// | Author: huang <2374266244@qq.com>
// +----------------------------------------------------------------------
'use strict';
import Base from './base.js';

export default class extends Base {
  // 获取品牌列表
  async productlistAction() {
    const page = this.post();
    const pages = page.pages;
    const limits = page.limits;
    const search = page.search;
    const zt = page.zt;
    const shopid = this.userinfo.departmentid;

    const data = await this.model('or_goods')
      .alias('g')
      .field('g.*,b.name as bname,c.name as cname')
      .join('`think_or_brand` b on b.id=g.brandid')
      .join('`think_or_subjectcategory` c on c.id=g.categoryid')
      .page(pages, limits)
      .order('g.id DESC')
      .where({ 'g.departmentid': shopid, 'g.isdisabled': zt, 'g.name|g.number': ['like', '%' + search + '%'] })
      .countSelect();

    return this.json(data);
  }

  async getgoodsconfigAction() {
    const subjectid = this.post().subjectid;
    const shopid = this.userinfo.departmentid;
    const data = await this.model('or_subject_config')
      .alias('sc')
      .field('sc.*,sl.name')
      .join('`think_or_subject_childclass` sl on sc.subjectchildclassid=sl.id')
      .where({ 'sc.subjectid': subjectid, 'sc.departmentid': shopid, 'sc.type': 1 })
      .select();

    return this.json(data);
  }

  // 获取产品对应的品牌列表
  async getbrandAction() {
    if (this.isPost) {
      const belongsid = JSON.parse(this.post('id'));
      let data = [];
      if (!think.isEmpty(belongsid)) {
        data = await this.model('or_brand').where({ id: ['IN', belongsid] }).select();
      }
      return data ? this.json(data) : this.fail({ info: '无品牌' });
    } else {
      const data = await this.model('or_brand').where({ departmentid: this.userinfo.departmentid }).select();
      return this.json(data);
    }
  }

  // 获取产品机构分类和品牌
  async getbelongsAction() {
    const shopid = this.userinfo.departmentid;
    const catelist = await this.model().query('select * from `think_or_subjectcategory` where departmentid=' + shopid + ' and pid!=0');
    const brandlist = await this.model().query('select * from `think_or_brand` where departmentid=' + shopid);
    const data = {
      cl: catelist,
      bl: brandlist
    };
    return this.json(data);
  }

  // 停用、启用产品
  async goodsstatusAction() {
    const id = this.post('id');
    const st = this.post('st');
    const laqu = await this.ispull(id);
    if (!think.isEmpty(laqu)) {
      return this.fail(laqu.msg);
    }
    const res = await this.model('or_goods').where({ id: id }).update({ isdisabled: st });
    if (st * 1) {
      return res ? this.success('停用成功') : this.fail('停用失败');
    } else {
      return res ? this.success('启用成功') : this.fail('启用失败');
    }
  }

  // 添加/编辑产品
  async addeditAction() {
    const data = this.post();
    const subInfo = data.subInfo;
    const subConfig = data.subConfig;
    const orid = this.userinfo.departmentid;
    const addtime = Math.round(new Date().valueOf() / 1000);

    // 判断产品名称是否重复
    const repeat = await this.model('or_goods').where('departmentid="' + orid + '" AND (name="' + subInfo.name + '" OR number="' + subInfo.number + '") AND id!="' + subInfo.id + '"').select();

    if (!think.isEmpty(repeat)) {
      return this.fail('名称或编号重复');
    }

    // if (data.tdtype == 1) {
    //   data.percent = Number(data.percent / 100).toFixed(2);
    //   data.fixed = 0;
    // } else {
    //   data.percent = 0;
    //   data.fixed = data.fixed;
    // }

    // if (data.khtdtype == 1) {
    //   data.khpercent = Number(data.khpercent / 100).toFixed(2);
    //   data.khfixed = 0;
    // } else {
    //   data.khpercent = 0;
    //   data.khfixed = data.khfixed;
    // }

    const model = this.model('or_goods');
    const addsubConfig = [];
    if (subInfo.id * 1) {
      // 编辑项目
      let flag = true;
      const insertsub = [];
      const updatesub = [];
      const reducesub = [];
      const subconfclassidlists = [];
      const getFieldata = await this.model('or_subject_config').where({ subjectid: subInfo.id, type: 1, departmentid: orid }).getField('subjectchildclassid,id');
      const subconflists = getFieldata.subjectchildclassid;
      const subconfidlists = getFieldata.id;
      subConfig.forEach((v) => {
        subconfclassidlists.push(v.subjectchildclassid);
      });
      subConfig.forEach((v) => {
        if (subconflists.includes(v.subjectchildclassid)) {
          delete (v['name']);
          v['id'] = subconfidlists[subconflists.indexOf(v.subjectchildclassid)];
          updatesub.push(v);
        } else {
          insertsub.push({
            subjectid: subInfo.id,
            subjectchildclassid: v.subjectchildclassid,
            type: 1,
            departmentid: orid,
            // xjyjtype: v.xjyjtype,
            xjyjpercent: v.xjyjpercent,
            // xjyjfixed: v.xjyjfixed,
            xjtctype: v.xjtctype,
            xjtcpercent: v.xjtcpercent,
            xjtcfixed: v.xjtcfixed,
            // khyjtype: v.khyjtype,
            khyjpercent: v.khyjpercent,
            // khyjfixed: v.khyjfixed,
            khtctype: v.khtctype,
            khtcpercent: v.khtcpercent,
            khtcfixed: v.khtcfixed
            // minuscost: v.minuscost
          });
        }
      });
      subconflists.forEach((v) => {
        if (!subconfclassidlists.includes(v)) {
          reducesub.push(v);
        }
      });
      await model.transaction(async() => {
        try {
          const upsubIfnum = await model.where({ id: subInfo.id }).update(subInfo);
          if (insertsub.length !== 0) {
            const return1 = await this.model('or_subject_config').db(model.db()).addMany(insertsub);
            if (!return1) { flag = false };
          }
          if (updatesub.length !== 0) {
            const return2 = await this.model('or_subject_config').db(model.db()).updateMany(updatesub);
            if (!return2) { flag = false };
          }
          if (reducesub.length !== 0) {
            const return3 = await this.model('or_subject_config').db(model.db()).where({ subjectid: subInfo.id, subjectchildclassid: ['in', reducesub], type: 1, departmentid: orid }).delete();
            if (!return3) { flag = false };
          }
          if (upsubIfnum && flag) {
            await model.commit();
            return this.success('更新成功!');
          } else {
            await model.rollback();
            return this.fail('更新失败!');
          }
        } catch (e) {
          await model.rollback();
          return this.fail('更新失败!');
        }
      });
    } else {
      // 添加项目
      const addsubInfo = {
        name: subInfo.name,
        price: subInfo.price,
        remarks: subInfo.remarks,
        departmentid: orid,
        addtime: addtime,
        brandid: subInfo.brandid,
        categoryid: subInfo.categoryid,
        nums: subInfo.nums,
        number: subInfo.number,
        organizationprice: subInfo.organizationprice,
        shopprice: subInfo.shopprice
        // tdtype: data.tdtype,
        // percent: data.percent,
        // fixed: data.fixed,
        // khtdtype: data.khtdtype,
        // khpercent: data.khpercent,
        // khfixed: data.khfixed,
      };
      await model.transaction(async() => {
        try {
          // 写入数据库
          const subjectid = await model.add(addsubInfo);
          subConfig.forEach((v) => {
            addsubConfig.push({
              subjectid: subjectid,
              subjectchildclassid: v.subjectchildclassid,
              type: 1,
              departmentid: orid,
              // xjyjtype: v.xjyjtype,
              xjyjpercent: v.xjyjpercent,
              // xjyjfixed: v.xjyjfixed,
              xjtctype: v.xjtctype,
              xjtcpercent: v.xjtcpercent,
              xjtcfixed: v.xjtcfixed,
              // khyjtype: v.khyjtype,
              khyjpercent: v.khyjpercent,
              // khyjfixed: v.khyjfixed,
              khtctype: v.khtctype,
              khtcpercent: v.khtcpercent,
              khtcfixed: v.khtcfixed
              // minuscost: v.minuscost
            });
          });
          // 写入数据库
          const subjectconfigid = await this.model('or_subject_config').db(model.db()).addMany(addsubConfig);
          if (subjectid && subjectconfigid) {
            await model.commit();
            return this.success('添加成功!');
          } else {
            await model.rollback();
            return this.fail('添加失败!');
          }
        } catch (e) {
          await model.rollback();
          return this.fail('添加失败！');
        }
      });
    }
  }

  // 如果分店拉取机构产品，则机构产品不能操作
  async ispull(goodsid) {
    const isuse = await this.model('or_shop_goods').where({ goodsid: goodsid }).select();
    if (!think.isEmpty(isuse)) {
      return { msg: '分店拉取的产品不能操作' };
    }
  }

  // 获取商品的详细信息
  async getGoodsInfoAction() {
    const goodsid = this.get().id;
    const info = await this.model('or_goods').where({ id: goodsid }).find();
    if (info.banner) {
      info.banner = JSON.parse(info.banner);
    }
    return this.json(info);
  }

  // 保存商品的详细信息
  async saveGoodsInfoAction() {
    const data = this.post();
    data.banner = JSON.stringify(data.banner);
    const res = await this.model('or_goods').where({ id: data.goodsid }).update(data);
    return res ? this.success('操作成功') : this.fail('操作失败');
  }

  // 获取产品下子类
  async getgoodsChildClassAction() {
    const orid = this.userinfo.departmentid;
    const info = await this.model('or_subject_childclass').where({ departmentid: orid, type: 1 }).select();
    return this.json(info);
  }
}
